package _1_leetcode_1_20._14最长公共前缀;

import java.util.ArrayList;
import java.util.List;

/**
 * 编写一个函数来查找字符串数组中的最长公共前缀。
 *
 * 如果不存在公共前缀，返回空字符串 ""。
 * https://leetcode-cn.com/problems/longest-common-prefix/
 *@描述 
 *@参数
 *@返回值  
 *@创建人  mazexal
 *@创建时间  2021/1/5
 */
public class Solution {
    public static void main(String[] args) {
        String[] inuput = new String[]{"dog"};
        System.out.println(longestCommonPrefix(inuput));
    }


    public static String longestCommonPrefix(String[] strs) {
        if(strs.length==0){
            return "";
        }
        List<Character> characterList = new ArrayList();
        int begin = 0;
        boolean flag = true;
        while (flag) {
            char character = 0;
            for (int i = 0; i < strs.length; i++) {
                if (begin > strs[i].length() - 1) {
                    flag = false;
                    break;
                }
                if (i == 0) {
                    character = strs[i].charAt(begin);
                }
                char tmp = strs[i].charAt(begin);
                if (tmp != character) {
                    flag = false;
                    break;
                }
                if (i == strs.length - 1) {
                    begin++;
                    characterList.add(character);
                }
            }
        }
        StringBuilder stringBuilder = new StringBuilder();
        for (Character item : characterList) {
            stringBuilder.append(item);
        }
        return stringBuilder.toString();
    }

}
